layui.use(['form','layer'],function(){
	
	 var form = layui.form,layer = layui.layer;
	 var dg =  document.getElementById("dg");
	 Sortable.create(dg);
	 
	  var inputRequired,inputCol,outputCol,operateDataUrl,expectDataUrl
	  ,inputPlaceHolder,outputPlaceHolder,inputControlSelect,inputControlSelect2;
	  
	 $.getJSON ("../dict/case.json","", function (data) {  
		    inputRequired = data.inputRequired;
		    inputCol = data.inputCol;
		    outputCol = data.outputCol;
		    inputPlaceHolder = data.inputPlaceHolder;
		    outputPlaceHolder = data.outputPlaceHolder;
		    inputControlSelect = data.inputControlSelect;
		    inputControlSelect2 = data.inputControlSelect2;
		    operateDataUrl = data.operateDataUrl;
		    expectDataUrl = data.expectDataUrl;
		    controlRequired = data.controlRequired;
		    form.render();
     });
	
	$("#save-btn").on('click',function(){save();});
	$("#del-btn").on('click',function(){del();});
	$("#act-btn").on('click',function(){preview();});
	$("#imp-btn").on('click',function(){imp();});
	form.on('select(appId)',function(){
		clearInput($("#dg"));
		clearOutput($("#dg"));
	});
	 
	form.on("select(operate-input)",function(data){
	 
	  var val = data.value;
	  var datainput = $(this).closest("tr").find("input[name='data-input']");
	  if(!isBlank(inputPlaceHolder[val])){
		  datainput.attr('placeHolder',inputPlaceHolder[val]);
	  }else
		  datainput.attr('placeHolder',"");
	  
	  clearInput($(this).closest("tr"));
	});
    
	
	function clearInput(datainput){
		datainput.find("input[name='operateControlId']").val("");
		datainput.find("input[name='control-input-name']").val("");
		datainput.find("input[name='operateData']").val("");
		datainput.find("input[name='operateRule']").val("");
		datainput.find("input[name='data-input']").val("");
		datainput.find("input[name='waitingSecs']").val("");
		
	}
	
	form.on('select(expect-output)',function(data){
	 var val = data.value;
	 var dataoutput = $(this).closest("tr").find("input[name='data-output']");
	 if(!isBlank(outputPlaceHolder[val])){
		 dataoutput.attr('placeHolder',outputPlaceHolder[val]);
	 }else
		 dataoutput.attr('placeHolder',"");
	 clearOutput($(this).closest("tr"));
	});
	
	form.on("checkbox(selall-btn)",function(){
		 $("input[name='stepcheckbox']").prop("checked",$("#selall-btn").prop("checked"));
		 form.render("checkbox");
	});
	
	function clearOutput(dataoutput){
		dataoutput.find("input[name='outputData']").val("");
		dataoutput.find("input[name='data-output']").val("");
	}
	
	$("#add-btn").on('click',function(){
		addStep();
	});
	
	initCase();
	function initCase(){
		var caseId = $("#caseId").val();
		var data = {'caseId':caseId};
		ajaxPost('../case/getCaseById',data,
				function(data){
					var caseData = data.data;
					var controlJson = data.controlJson;
					var paraJson = data.paraJson;
					initCaseMain(caseData);
					initStep(caseData.stepList,controlJson,paraJson);
					form.render('select');
					form.render('checkbox');
			
				},
				function(data){
					 parent.layer.alert(data.errorMsg, {
       					icon: 5,
       					title: "错误"
       					});
				 
				});
	}
	
	
	function initCaseMain(data){
		
		$("#appId").val(data.appId);
		$("#caseName").val(data.caseName);
		$("#caseType").val(data.caseType);
		$("#caseStatus").val(data.editStatus);
		$("#caseNumber").val(data.caseNumber);
		
	}
	
	 //引入
	  function imp(){
		  var appId = $("#appId").val();
		  x_admin_show("脚本演示","../case/toImp?appId="+appId,null,null,true);
	  }
	  
	  
	  function appendCaseStep(caseId){
		  ajaxPost("../case/getStepByCaseId",{"caseId":caseId},
				  function(data){
			        var steplist = data.data;
			        var controlJson = data.controlJson;
					var paraJson = data.paraJson;
					initStep(steplist,controlJson,paraJson);
					form.render('select');
					form.render('checkbox');
		  			},
				  function(data){
					 parent.layer.alert(data.errorMsg, {
	 					icon: 5,
	 					title: "错误"
	 					});
		  		});
		  
	  }
	  
	  window.appendCaseStep = appendCaseStep;
	  
	  
	function initStep(steplist,controlJson,paraJson){
		$("#dg").empty();
		for(var i = 0 ;i < steplist.length; i ++){
			var step = steplist[i];
			var content = [];
			content.push('<tr>');
			content.push('<td><input type="checkbox" name="stepcheckbox" lay-skin="primary"/></td>');
			content.push('<td>');
			content.push('<select lay-filter="operate-input" name = "operateType">');
			
			var operateType = step.operateType;
			content.push(operateType == 1?'<option value="1" selected>点击</option>':'<option value="1">点击</option>');	
			content.push(operateType == 2?'<option value="2" selected>长按</option>':'<option value="2">长按</option>');
			content.push(operateType == 3?'<option value="3" selected>输入</option>':'<option value="3">输入</option>');			    
			content.push(operateType == 4?'<option value="4" selected>读取</option>':'<option value="4">读取</option>');		
			content.push(operateType == 5?'<option value="5" selected>滚动区域搜索</option>':'<option value="5">滚动区域搜索</option>');
			content.push(operateType == 6?'<option value="6" selected>内容匹配点击</option>':'<option value="6">内容匹配点击</option>');				
			content.push(operateType == 7?'<option value="7" selected>图片匹配点击</option>':'<option value="7">图片匹配点击</option>');			
			content.push('</select>');				
			content.push('</td>');
			
			var operateControlId = step.operateControlId;
			var operateControlName = controlJson[operateControlId];
			content.push('<td><input type="hidden" name="operateControlId" value="'+showStr(operateControlId)+'"/><input type="text" class="layui-input" name="control-input-name" onclick="selectCtrl(this)" value="'+showStr(operateControlName)+'" readonly/></td>');				
			
			var operateData = isBlank(step.operateReadParaId)?step.operateWriteParaId:step.operateReadParaId;		
			var operateDataName = paraJson[operateData];
			var operateRule = step.operateReadRule;
			content.push('<td><input type="hidden" name="operateData" value="'+showStr(operateData)+'"/><input type="hidden" name="operateRule" value="'+showStr(operateRule)+'"/><input type="text" class="layui-input" name="data-input" onclick="selectData(this)"  value="'+showStr(operateDataName)+'" readonly/></td>');
				
			content.push('<td><input type="text" class="layui-input" name="waitingSecs" value="'+showStr(step.waitingSecs)+'"/></td>');
			content.push('<td>');	
			content.push('<select lay-filter="expect-output" name="expectType">');
			
			var expectType = step.expectType;
			content.push(expectType == 1?'<option value="1" selected>无</option>':'<option value="1">无</option>');		    
			content.push(expectType == 2?'<option value="2" selected>文本内容包含</option>':'<option value="2">文本内容包含</option>');			  
			content.push(expectType == 3?'<option value="3" selected>发现控件</option>':'<option value="3">发现控件</option>');			  
			content.push(expectType == 4?'<option value="4" selected>变量运算</option>':'<option value="4">变量运算</option>');			  
			content.push('</select>');			  
			content.push('</td>');	
			
			var outputData = !isBlank(step.expectControlId)?step.expectControlId:(!isBlank(step.expectReadParaId)?step.expectReadParaId:step.expectParaOperation);
			var outputName = !isBlank(step.expectControlId)?controlJson[step.expectControlId]:(!isBlank(step.expectReadParaId)?paraJson[step.expectReadParaId]:step.expectParaOperation);
			content.push('<td><input type="hidden" name="outputData" value="'+showStr(outputData)+'"/><input type="text" class="layui-input" name="data-output" value="'+showStr(outputName)+'" onclick="selExpect(this)" readonly /></td>');		 
			content.push('</tr>');
			
			$("#dg").append(content.join(""));
		}
	}
	
	function addStep(){
		var stepEle = $("#dg>tr:eq(0)").clone();
		$("#dg").append(stepEle);
		clearInput(stepEle);
		clearOutput(stepEle);
		stepEle.find("input[name='data-input']").attr("placeHolder","");
		stepEle.find("select[name='operateType']").val(1);
		form.render('select');
		form.render('checkbox');
	}
	
	
	function getCaseData(){
		
		var data = {};
		
		var id = $("#caseId").val();
		data['id'] = id;
		
		var appId = $("#appId").val();
		data['appId'] = appId;
		
		var caseName = $("#caseName").val();
		if(isBlank(caseName)){
			layer.tips("请填写案例名称","#caseName",{
      			  tips: [1, '#FF0000'],
      			  time: 3000
      			});
      		return false;
		}
		
		data['caseName'] = caseName;
		
		
		var caseType = $("#caseType").val();
		data['caseType'] = caseType;
		
		var caseStatus = $("#caseStatus").val();
		data['editStatus'] = caseStatus;
		
		return data;
	}
	
	
	
	function getStepData(){
		
		var data = [];
		var isValidated = true;
		$("#dg>tr").each(function(index){
			
			var step = {};
			//案例次序
			var stepOrder = index+1;
			step['stepOrder'] = stepOrder;
			
			//操作类型
			var operateType = $(this).find("select[name='operateType']").val();
			step['operateType'] = operateType;
			
			//操作控件
			var control = $(this).find("input[name='operateControlId']");
			var controlName = $(this).find("input[name='control-input-name']");
			var operateControlId = control.val();
			if(controlRequired[operateType] == 1 && isBlank(operateControlId)){
				layer.tips("请选择控件",controlName,{
      			  tips: [1, '#FF0000'],
      			  time: 3000
      			});
			isValidated = false;
      		return false;
			}
			if(controlRequired[operateType] == 1 && !isBlank(operateControlId))
			step['operateControlId'] = operateControlId;
			
			
			//操作数据
			var operateData = $(this).find("input[name='operateData']").val();
			var operateDataInput = $(this).find("input[name='data-input']");
			if(inputRequired[operateType] == 1 && isBlank(operateData)){
				layer.tips("请选择操作数据",operateDataInput,{
      			  tips: [1, '#FF0000'],
      			  time: 3000
      			});
			isValidated = false;
      		return false;
			}
			if(inputRequired[operateType] == 1 && !isBlank(inputCol[operateType]))
				step[inputCol[operateType]] = operateData;
			
			//读取规则
			var operateRule = $(this).find("input[name='operateRule']").val();
			if(!isBlank(operateRule))
				step['operateReadRule']=operateRule;
			//延迟
			var waitingSecsInput = $(this).find("input[name='waitingSecs']");
			var waitingSecs = waitingSecsInput.val();
			if(isBlank(waitingSecs)){
				layer.tips("请填写操作延迟",waitingSecsInput,{
      			  tips: [1, '#FF0000'],
      			  time: 3000
      			});
			isValidated = false;
      		return false;
			}
			step['waitingSecs'] = waitingSecs;
			
			
			//期望结果类型
			var expectType = $(this).find("select[name='expectType']").val();
			if(!isBlank(expectType))
				step['expectType'] = expectType;
			
			
			//期望结果
			var dataOut = $(this).find("input[name='data-output']");
			var expectResult = $(this).find("input[name='outputData']").val();
			if(!isBlank(expectType)  &&expectType != 1  && isBlank(expectResult)){
				layer.tips("请选择期望结果",dataOut,{
      			  tips: [1, '#FF0000'],
      			  time: 3000
      			});
			isValidated = false;
      		return false;
			}
			if(!isBlank(expectType) && !isBlank(outputCol[expectType]))
				step[outputCol[expectType]] = expectResult;
			
			data.push(step);
			
			
		});
		
		if(!isValidated)
			data = [];
		
		return data;
		
	}
	
	function save(){
		
		var caseData = getCaseData();
        if(!caseData)		
			return false;
		var caseJson = JSON.stringify(caseData);
		
		var caseStep = getStepData();
		if(!caseStep || caseStep.length == 0)
			return false;
		
		var stepJson = JSON.stringify(caseStep);
		
		var data = {'caseJson':caseJson,'stepJson':stepJson};
		ajaxPost('../case/updateCase',data,
		         function(data){
					 var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            		 parent.layer.close(index);
            		 parent.initPage();
				 },
				 function(data){
					 parent.layer.alert(data.errorMsg, {
        					icon: 5,
        					title: "错误"
        					});
				 });
		
	}
	
  function del(){
	  var len = $("#dg>tr").length;
	  var selLen = $("input[name='stepcheckbox']:checked").length;
	  if(selLen == 0){
		  parent.layer.alert("请选择需要删除的步骤", {
				icon: 5,
				title: "错误"
				});
		  return false;
	  }
	  
	  if(selLen == len){
		  parent.layer.alert("请保留至少一条案例步骤", {
				icon: 5,
				title: "错误"
				});
		  return false;
	  }
	  $("input[name='stepcheckbox']:checked").each(function(){
		  $(this).closest("tr").remove();
	  });
  }
 //输入控件
  function selectCtrl(obj){
	  var closestTr = $(obj).closest("tr");
	  var index = closestTr.index();
	  var appId = $("#appId").val();
	  var operateType = closestTr.find("select[name='operateType']").val();
	  if(isBlank(operateType))
		  return false;
	  var operateControlId = closestTr.find("input[name='operateControlId']").val();
	  var types = inputControlSelect[operateType] == null?"":inputControlSelect[operateType].join(",");
	  var locateTypes = inputControlSelect2[operateType] == null?"":inputControlSelect2[operateType].join(",");
	  x_admin_show("选择控件","../case/selectCtrl?appId="+appId+"&types="+types+"&locateTypes="+locateTypes+"&index="+index+"&selectType=2&controlId="+operateControlId,400,400);
  }
  
  window.selectCtrl = selectCtrl;
  
  //输入参数
  function selectData(obj){
	  var closestTr = $(obj).closest("tr");
	  var index = closestTr.index();
	  var operateType = closestTr.find("select[name='operateType']").val();
	  if(isBlank(operateType))
		  return false;
	  if(isBlank(operateDataUrl[operateType]))
		  return false;
	  var operateData = closestTr.find("input[name='operateData']").val();
	  var operateRule = closestTr.find("input[name='operateRule']").val();
	  x_admin_show("选择数据",operateDataUrl[operateType]+"?index="+index+"&selectType=2&operateData="+operateData+"&operateRule="+operateRule,null,null,true);
  }
  window.selectData = selectData;
  
  
  
  //输出
  function selExpect(obj){
	  var closestTr = $(obj).closest("tr");
	  var index = closestTr.index();
	  var appId = $("#appId").val();
	  var expectType = closestTr.find("select[name='expectType']").val();
	  if(isBlank(expectType))
		  return false;
	  if(isBlank(expectDataUrl[expectType]))
		  return false;
	  
	  var outputData = closestTr.find("input[name='outputData']").val();
	  if(expectType == 3){
		  x_admin_show("期望结果",expectDataUrl[expectType]+"?index="+index+"&appId="+appId+"&locateTypes=1,3&selectType=1&controlId="+outputData,400,400);
	  }
		  
	  else
		  x_admin_show("期望结果",expectDataUrl[expectType]+"?index="+index+"&selectType=1&operateData="+outputData,null,null,true);
  }
  window.selExpect = selExpect;
  
//输入控件
  function preview(){
	  //x_admin_show("脚本预览","../script/toDemonstration",700,600);
	  var caseId = $("#caseId").val();
	  var caseData = getCaseData();
      if(!caseData)		
			return false;
      var caseJson = JSON.stringify(caseData);
		
      var caseStep = getStepData();
      if(!caseStep || caseStep.length == 0)
			return false;
		
      var stepJson = JSON.stringify(caseStep);
		
      var data = {'caseJson':caseJson,'stepJson':stepJson};
      ajaxPost('../case/updateCase',data,
		         function(data){
			x_admin_show("脚本演示","../case/toShow?caseId="+caseId,null,null,true);
				},
				 function(data){
					 parent.layer.alert(data.errorMsg, {
      					icon: 5,
      					title: "错误"
      					});
				 });
	   
  }
});